//
//  MyEmotionViewController.m
//  Games
//
//  Created by iOS Three on 14/12/25.
//  Copyright (c) 2014年 iOS Two. All rights reserved.
//

#import "MyEmotionViewController.h"
#import "EmotionDeatilViewController.h"
#import "myObj.h"
#import "myData.h"
#define kHEIGHT self.view.frame.size.height
#define KWIDTH self.view.frame.size.width
#define FONT [UIFont fontWithName:@"MFYaYuan_Noncommercial-Regular" size:20]

@interface MyEmotionViewController ()

@end

@implementation MyEmotionViewController

- (void)viewDidLoad {
    [self findSQL];
    [super viewDidLoad];
    self.navigationItem.title = @"我的表情包";

    UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 100, 20)];
    label.text = @"我的表情包";
    label.font = FONT;
    label.textColor = [UIColor colorWithRed:0.98 green:0.59 blue:0.16 alpha:1];
    label.textAlignment = NSTextAlignmentCenter;
    self.navigationItem.titleView = label;
    // Do any additional setup after loading the view.
    
    _leftBt = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"iconfont-shanchu"] style:UIBarButtonItemStyleDone target:self action:@selector(delete:)];
    
    _leftBt.tag = 1111;
    self.navigationController.navigationBar.tintColor = [UIColor colorWithRed:0.98 green:0.59 blue:0.16 alpha:1];
    self.navigationItem.rightBarButtonItem = _leftBt;
    
    [self.view setBackgroundColor:[UIColor whiteColor]];
    _buttonArray = [[NSMutableArray alloc] init];
    [self createViewAndKit];
    
   
}

- (KRLCollectionViewGridLayout *)layout
{
    return (id)self.mainCollection.collectionViewLayout;
}

-(void)findSQL {
    _collectGifName = [[NSMutableArray alloc]init];
    _collectGifCover = [[NSMutableArray alloc]init];
    myData *data = [[myData alloc]init];
    [data initData];
    NSArray *array = [data selectData];
    for (int i = 0; i < array.count; i++) {
        myObj *obj = [array objectAtIndex:i];
        [_collectGifName addObject:obj.gifName];
        [_collectGifCover addObject:obj.gifImage];
    }
    NSLog(@"%@    \n      %@",_collectGifName,_collectGifCover);
}


-(void)createViewAndKit {
    
    UIImageView *headerImg = [[UIImageView alloc] init];
    [headerImg setFrame:CGRectMake(0, 0, KWIDTH, kHEIGHT)];
    headerImg.image = [UIImage imageNamed:@"di6_02@3x"];
    [self.view addSubview:headerImg];
    
    KRLCollectionViewGridLayout *flowLayout=[[KRLCollectionViewGridLayout alloc]init];
    [flowLayout setScrollDirection:UICollectionViewScrollDirectionVertical];
    
    _mainCollection = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 64, KWIDTH, kHEIGHT - 35) collectionViewLayout:flowLayout];
    //注册
    [_mainCollection registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"cell"];
    //设置代理
    _mainCollection.delegate = self;
    _mainCollection.dataSource = self;
    _mainCollection.backgroundColor = [UIColor clearColor];
    [self.view addSubview:_mainCollection];
    if (KWIDTH <= 320) {
        self.layout.numberOfItemsPerLine = 3;
        self.layout.sectionInset = UIEdgeInsetsMake(25, 25, 20, 20);
        self.layout.interitemSpacing = 25;
        self.layout.lineSpacing = 5;
    }else{
        self.layout.numberOfItemsPerLine = 4;
        self.layout.sectionInset = UIEdgeInsetsMake(25, 25, 20, 20);
        self.layout.interitemSpacing = 7;
        self.layout.lineSpacing = 15;
    }

    self.layout.aspectRatio = 0.72;
   
    
    _emotionArray = [[NSMutableArray alloc] initWithObjects:@"抱抱",@"讨好",@"装逼", nil];
    _emotionName = [[NSMutableArray alloc] initWithObjects:@"阿狸",@"丘比猫",@"小幺鸡", nil];
}
#pragma UICollectionView

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    if (_emotionArray.count != 0) {
        return _collectGifCover.count;
    }
    return 0;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];

    UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(deleteCell:)];
    
    UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 75, 75)];
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
    NSString *uniquePath=[[paths objectAtIndex:0] stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.gif",[_collectGifCover objectAtIndex:indexPath.row]]];
    [imageView setImage:[UIImage imageWithData:[NSData dataWithContentsOfFile:uniquePath]]];
    imageView.layer.cornerRadius = 8;
    imageView.layer.masksToBounds = YES;
    imageView.backgroundColor = [UIColor whiteColor];
    imageView.userInteractionEnabled = YES;
    imageView.layer.borderWidth = 1;
    imageView.backgroundColor = [UIColor whiteColor];
    imageView.layer.borderColor = [[UIColor colorWithRed:0.94 green:0.91 blue:0.61 alpha:1]CGColor];
    [imageView addGestureRecognizer:longPress];
    
    UIButton *deleteBt = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    [deleteBt setFrame:CGRectMake(56, 0, 20, 20)];
    [deleteBt setBackgroundImage:[UIImage imageNamed:@"deleteImg"] forState:UIControlStateNormal];
    deleteBt.tag = indexPath.row;
    if (_leftBt.tag == 2222) {
        deleteBt.hidden =  NO;
        [deleteBt addTarget:self action:@selector(deleteEmotion:) forControlEvents:UIControlEventTouchUpInside];
    }else
    deleteBt.hidden = YES;
    [_buttonArray addObject:deleteBt];
    [imageView addSubview:deleteBt];
    
    _titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 75, 75, 30)];
    if (_collectGifName.count != 0) {
        _titleLabel.text = [_collectGifName objectAtIndex:indexPath.row];

    }
    _titleLabel.textAlignment = NSTextAlignmentCenter;
    _titleLabel.font = [UIFont fontWithName:@"MFYaYuan_Noncommercial-Regular" size:15];
    _titleLabel.textColor = [UIColor colorWithRed:0.95 green:0.62 blue:0.21 alpha:1];
    _titleLabel.backgroundColor = [UIColor colorWithRed:0.94 green:0.91 blue:0.61 alpha:1];
    
    [cell addSubview:imageView];
    [cell addSubview:_titleLabel];
    cell.contentView.backgroundColor = [UIColor colorWithRed:0.94 green:0.91 blue:0.61 alpha:1];
    
    _index = indexPath;
    
    return cell;
}

-(void)deleteCell:(UILongPressGestureRecognizer *)gesture {
    for (int i = 0; i < _buttonArray.count; i++) {
        UIButton *button = [_buttonArray objectAtIndex:i];
        button.hidden = NO;
        [button addTarget:self action:@selector(deleteEmotion:) forControlEvents:UIControlEventTouchUpInside];
    }
}


-(void)delete:(id)sender {
    UIBarButtonItem *button = (UIBarButtonItem *)sender;
    if (button.tag == 1111) {
        for (int i = 0; i < _buttonArray.count; i++) {
            UIButton *button = [_buttonArray objectAtIndex:i];
            button.hidden = NO;
            [button addTarget:self action:@selector(deleteEmotion:) forControlEvents:UIControlEventTouchUpInside];
//            _leftBt.title = @"完成";
        }
        [button setTag:2222];
    }else{
        for (int i = 0; i < _buttonArray.count; i++) {
            UIButton *button = [_buttonArray objectAtIndex:i];
            button.hidden = YES;
            [button addTarget:self action:@selector(deleteEmotion:) forControlEvents:UIControlEventTouchUpInside];
//            _leftBt.title = @"删除";
        }
        [button setTag:1111];
    }
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    EmotionDeatilViewController *emotionDeatil = [[EmotionDeatilViewController alloc] init];
    emotionDeatil.gifName = [_collectGifName objectAtIndex:indexPath.row];
    [self.navigationController pushViewController:emotionDeatil animated:YES];
}


-(void)deleteEmotion:(id)sender {
    UIButton *button = (UIButton *)sender;
    _deleteArray = [[NSMutableArray alloc] init];
    myData *mySql = [[myData alloc] init];
    [mySql initData];
    NSLog(@"%@",[_collectGifName objectAtIndex:button.tag]);
    _deleteArray = [mySql selectEmotion:[_collectGifName objectAtIndex:button.tag]];
    NSLog(@"%@",_deleteArray);
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
    for (int i = 0; i < _deleteArray.count; i++) {
        NSString *uniquePath=[[paths objectAtIndex:0] stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.gif",[_deleteArray objectAtIndex:i]]];
        NSFileManager *fileMgr = [NSFileManager defaultManager];
        BOOL bRet = [fileMgr fileExistsAtPath:uniquePath];
        if (bRet) {
            //
            NSError *err;
            [fileMgr removeItemAtPath:uniquePath error:&err];
        }
    }
    [mySql deleteEmotion:[_collectGifName objectAtIndex:button.tag]];
    [mySql deletebiaoQingBao:[_collectGifName objectAtIndex:button.tag]];
    [_collectGifName removeObjectAtIndex:button.tag];
    [_collectGifCover removeObjectAtIndex:button.tag];
    [_mainCollection reloadData];
}

- (UICollectionViewLayoutAttributes*)initialLayoutAttributesForAppearingItemAtIndexPath:(NSIndexPath *)itemIndexPath
{
    UICollectionViewLayoutAttributes *attr = [_mainCollection layoutAttributesForItemAtIndexPath:itemIndexPath];
    
    attr.transform = CGAffineTransformRotate(CGAffineTransformMakeScale(0.2, 0.2), M_PI);
    attr.center = CGPointMake(CGRectGetMidX(_mainCollection.bounds), CGRectGetMaxY(_mainCollection.bounds));
    
    return attr;
}

- (void)deleteItemsAtIndexPaths:(NSArray *)indexPaths {

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
